<?php
namespace app\clerk\controller;
use app\clerk\model\Category;
use app\clerk\model\Goods as GoodsModel;

/**
 * 菜品管理控制器
 */
class Goods extends Controller
{
    /**
     * 菜品列表(出售中)
     */
    public function index()
    {
		$shop_id = $this->shop_id;
        $model = new GoodsModel;
        $list = $model->getList($shop_id);
        return $this->fetch('index', compact('list'));
    }

    /**
     * 添加
     */
    public function add()
    {
		$shop_id = $this->shop_id;
        if (!$this->request->isAjax()) {
            // 分类
            $catgory = Category::getCacheTree($shop_id);
            return $this->fetch('add', compact('catgory'));
        }
        $model = new GoodsModel;
        if ($model->add($this->postData('goods'),$shop_id)) {
            return $this->renderSuccess('添加成功', url('goods/index'));
        }
        $error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }

    /**
     * 删除商品
     */
    public function delete($goods_id)
    {
        $model = GoodsModel::get($goods_id);
        if (!$model->remove()) {
            return $this->renderError('删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 编辑
     */
    public function edit($goods_id)
    {
		$shop_id = $this->shop_id;
        // 菜品详情
        $model = GoodsModel::detail($goods_id);
        if (!$this->request->isAjax()) {
            // 菜品分类
            $catgory = Category::getCacheTree($shop_id);
            // 多规格信息
            $specData = 'null';
            if ($model['spec_type'] == 20)
                $specData = json_encode($model->getManySpecData($model['spec_rel'], $model['spec']));
            return $this->fetch('edit', compact('model', 'catgory', 'specData'));
        }
        // 更新记录
        if ($model->edit($this->postData('goods'))) {
            return $this->renderSuccess('更新成功', url('goods/index'));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

}
